import java.util.HashMap;
import java.util.Map;

/**
 * 535. TinyURL 的加密与解密
 * https://leetcode-cn.com/problems/encode-and-decode-tinyurl/
 */
public class Solutions_535 {
    public static void main(String[] args) {
        String longUrl = "https://leetcode.com/problems/design-tinyurl";

        Codec_535 obj = new Codec_535();
        String shortUrl = obj.encode(longUrl);
        System.out.println(shortUrl);

        String res1 = obj.decode(shortUrl);
        System.out.println(res1);
    }
}

/**
 * 解法二：异或运算，获取相同长度的加密 url
 * 两个相同的数，异或为 0
 */
class Codec_535 {
    // 进行异或运算的质数
    int num = 1001;

    // Encodes a URL to a shortened URL.
    public String encode(String longUrl) {
        char[] arr = longUrl.toCharArray();
        for (int i = 0; i < arr.length; i++) {
            // 异或运算，得到新的字符
            arr[i] ^= num;
        }
        return String.valueOf(arr);
    }

    // Decodes a shortened URL to its original URL.
    public String decode(String shortUrl) {
        return encode(shortUrl);
    }
}


/**
 * 解法一：随机固定长度加密
 */
class Codec_535_2 {
    Map<String, String> map;
    // 62 个字符
    char[] chars;
    // 加密的长度
    int len;

    public Codec_535_2() {
        map = new HashMap<>();
        len = 6;
        chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
    }

    // Encodes a URL to a shortened URL.
    public String encode(String longUrl) {
        StringBuilder sb = new StringBuilder();
        sb.append("http://tinyurl.com/");
        for (int i = 0; i < len; i++) {
            double r = Math.random();
            int idx = (int) (r * 62);
//            sb.append(chars[random.nextInt(62)]);
            sb.append(chars[idx]);
        }

        String shortUrl = sb.toString();
        // 映射到 map 中，便于恢复
        map.put(shortUrl, longUrl);
        return shortUrl;
    }

    // Decodes a shortened URL to its original URL.
    public String decode(String shortUrl) {
        return map.getOrDefault(shortUrl, "");
    }
}
